package com.iflyun.rabbitmq.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.iflyun.rabbitmq.bean.Result;
import com.iflyun.rabbitmq.common.Common;




public class RabbitmqUtils {
	
   private final static Logger logger = LoggerFactory.getLogger(RabbitmqUtils.class);
	
	public static Result CheckQueue(){	  
        HttpResponse response = null;
        int statusCode = 0;
        try {
        	CloseableHttpClient Client =HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(Common.url);
            String up = Common.USERNAME+":"+Common.PASSWORD;
            //设置凭证
            String credentials = Base64.encodeBase64String(up.getBytes("UTF-8"));
            httpGet.setHeader("Authorization","Basic "+credentials);
            response = Client.execute(httpGet);
            //读取响应内容
            BufferedReader breader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuilder responseString = new StringBuilder();
            String line = null;
            while ((line = breader.readLine()) !=null) {
                responseString.append(line);
            }
            breader.close();
            String repsonseStr =responseString.toString();
            statusCode = response.getStatusLine().getStatusCode();
            logger.info("statusCode="+statusCode+" repsonseStr =" + repsonseStr);
        } catch (Exception e) {
        	logger.info("Could not connect to "+Common.url);
        	logger.error("队列监测异常:",e);
            //return new Result("1", Common.MQ_Queue_Fail, Common.Queue_Fail_MSG, "队列监测异常");
        }
        //响应码大于299要么代表错误，要么就是发送给客户端额外的指令
        if(statusCode>299){
            return new Result(statusCode+"", Common.MQ_Queue_Fail, Common.Queue_Fail_MSG, "队列监测异常");
        }
        return new Result(statusCode+"", Common.MQ_SUCCESS, Common.SUCCESS_MSG, "队列监测成功");
	}
		
	
}
